import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lzj_demo/bean/artical.dart';
import 'package:lzj_demo/bean/artical_type.dart';

import 'package:lzj_demo/network/api_service.dart';
import 'package:lzj_demo/pages/index/artical_detail.dart';
import 'package:lzj_demo/utils/route_util.dart';

//todo 首页
class IndexPage extends StatefulWidget {
  const IndexPage({super.key});

  @override
  State<StatefulWidget> createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  final List<Artical> _list = [];
  final List<ArticalType> _listType = [];
  int pageNum = 1;
  int _selectIndex = 0;
  double statusBarHeight = 0;

  //todo initState()是StatefulWidget的生命周期方法之一，在调用build()方法之前被调用。initState()只会在组件初始创建时被调用一次。
  @override
  void initState() {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
    getArticalList();
    getArticalTypeList();
    super.initState();
  }

  //todo 获取首页文章类型列表
  getArticalTypeList() async {
    List<ArticalType> list = await ApiService.getArticalTypeList({});
    setState(() {
      if (pageNum == 1) {
        _listType.clear();
      }
      _listType.addAll(list);
    });
  }

  //todo 获取首页文章列表
  getArticalList() async {
    List<Artical> list = await ApiService.getArticalList({});
    if (mounted) {
      setState(() {
        if (pageNum == 1) {
          _list.clear();
        }
        _list.addAll(list);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    //* 状态栏高度
    statusBarHeight = MediaQuery.of(context).padding.top;
    return Scaffold(
        appBar: null,
        body: Center(
          child: Column(
            children: [listViewType(), Expanded(child: listView())],
          ),
        ));
  }

  //todo 测试按钮
  Widget btn() {
    return Ink(
      width: 200,
      height: 50,
      color: Colors.purple,
      child: InkWell(
        onTap: getArticalList,
        child: const Text(
          "首页",
          style: TextStyle(
            fontSize: 18,
            color: Colors.black,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

//todo 横向类型列表
  Widget listViewType() {
    return Container(
      margin: EdgeInsets.only(top: statusBarHeight),
      padding: const EdgeInsets.fromLTRB(15, 0, 15, 0),
      height: 50,
      color: Colors.transparent,
      child: ListView.separated(
          scrollDirection: Axis.horizontal,
          itemBuilder: (context, index) {
            return GestureDetector(
                onTap: () {
                  setState(() {
                    _selectIndex = index;
                    pageNum = 1;
                    getArticalList();
                  });
                },
                child: Container(
                    margin: const EdgeInsets.only(right: 15),
                    child: Center(
                      child: Text(
                        _listType[index].name.toString(),
                        style: TextStyle(
                          fontSize: 15,
                          color: _selectIndex == index
                              ? Colors.purple
                              : Colors.grey,
                        ),
                      ),
                    )));
          },
          separatorBuilder: (context, index) {
            return const Divider();
          },
          itemCount: _listType.length),
    );
  }

  //todo 竖向列表
  Widget listView() {
    return Container(
        color: const Color(0xFFF1F4F6),
        // color: Colors.red,
        padding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
        child: EasyRefresh(
          onRefresh: () async {
            //  await Future.delayed(const Duration(seconds: 3));
            pageNum = 1;
            getArticalList();
          },
          onLoad: () async {
            pageNum++;
            getArticalList();
          },
          child: ListView.separated(
              itemBuilder: (context, index) {
                return GestureDetector(
                    onTap: () {
                      // ToastUtil.toast(_list[index].name);
                      //todo 跳转详情页
                      RouteUtil.push(
                          context,
                          ArticalDetailPage(
                              id: _list[index].id,
                              title: _list[index].contentTitle.toString()));
                    },
                    child: item(index));
              },
              separatorBuilder: (context, index) {
                return const Divider(
                  height: 12,
                  color: Colors.transparent,
                );
              },
              itemCount: _list.length),
        ));
  }

  //todo 列表item
  Widget item(index) {
    return ClipRRect(
      // 带圆角的用这个
      borderRadius: BorderRadius.circular(6),
      child: Container(
          color: Colors.white,
          padding: const EdgeInsets.fromLTRB(12, 16, 12, 16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start, //布局从起始位置开始
            children: [
              Row(
                children: [
                  // Container(
                  //   //给网络图片切圆形
                  //   width: 20,
                  //   height: 20,
                  //   clipBehavior: Clip.hardEdge,
                  //   decoration:
                  //       BoxDecoration(borderRadius: BorderRadius.circular(20)),
                  //   child: Image.asset("images/icon_head.png")
                  //   // CachedNetworkImage(
                  //   //   imageUrl: _list[index].headImg.toString(),
                  //   //   fit: BoxFit.cover,
                  //   // ),
                  // ),
                  Image.asset(
                    "images/icon_head.png",
                    width: 20,
                    height: 20,
                  ),
                  const SizedBox(width: 8), //横向间距
                  Text(
                    _list[index].name.toString(),
                    style: const TextStyle(fontSize: 14, color: Colors.grey),
                  ),
                ],
              ),
              const SizedBox(height: 8), //横向间距
              Row(
                children: [
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          _list[index].contentTitle.toString(),
                          style: const TextStyle(
                              fontSize: 16, color: Colors.black),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                        Container(
                            //可以设置间距
                            margin: const EdgeInsets.fromLTRB(0, 10, 0, 0),
                            child: Row(
                              children: [
                                Text(
                                  "${_list[index].readNum} 阅读",
                                  style: const TextStyle(
                                      fontSize: 12, color: Colors.grey),
                                ),
                                const SizedBox(width: 6), //横向间距
                                Text(
                                  "${_list[index].zanNum} 点赞",
                                  style: const TextStyle(
                                      fontSize: 12, color: Colors.grey),
                                ),
                                const SizedBox(width: 6), //横向间距
                                Text(
                                  "${_list[index].collectNum} 收藏",
                                  style: const TextStyle(
                                      fontSize: 12, color: Colors.grey),
                                ),
                              ],
                            ))
                      ],
                    ),
                  ),
                  const SizedBox(width: 8),
                  CachedNetworkImage(
                    imageUrl: _list[index].contentImg.toString(),
                    width: 60,
                    height: 60,
                    fit: BoxFit.cover,
                  )
                ],
              )
            ],
          )),
    );
  }
}
